#include "./dnswnd.h"
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdio.h>

#pragma comment(lib, "Ws2_32.lib")

using namespace MiniUI;
using namespace MiniUI::Type;

DNSWnd::DNSWnd()
{
    m_pWinView = WinView::CreateInstance();
    m_pWinView->SetWinBorder(MiniRect(0, 0, 0, 0));
    m_pWinView->OpenWindow(MiniRect(100, 100, 689, 546));

    Image* pBkg = Image::CreateInstance();
    pBkg->SetValue("wnd_bkg.png");
    pBkg->SetAnchors(UIObject::ANCHOR_LEFT | UIObject::ANCHOR_TOP | UIObject::ANCHOR_RIGHT | UIObject::ANCHOR_BOTTOM);
    pBkg->SetMargin(MiniRect(0, 0, 0, 0));
    pBkg->SetTransparent(true);
    m_pWinView->AddChild(pBkg);
    pBkg->Release();

    Button* pBtnClose = Button::CreateInstance();
    pBtnClose->OnClick += EventObject<OnClickEventFunc>(this, &DNSWnd::OnBtnCloseClick);
    pBtnClose->Init("btnclose_normal.png", "btnclose_hover.png", "btnclose_down.png");
    m_pWinView->AddChild(pBtnClose);
    pBtnClose->SetAnchors(UIObject::ANCHOR_TOP | UIObject::ANCHOR_RIGHT);
    pBtnClose->SetMargin(MiniRect(0, 1, 3, 0));
    pBtnClose->Release();

    Button* pBtnAnalyze = Button::CreateInstance();
    pBtnAnalyze->OnClick += EventObject<OnClickEventFunc>(this, &DNSWnd::OnBtnAnalyzeClick);
    pBtnAnalyze->Init("mybtn_normal.png", "mybtn_hover.png", "mybtn_down.png");
    pBtnAnalyze->SetText("analyze");
    m_pWinView->AddChild(pBtnAnalyze);
    pBtnAnalyze->SetPos(MiniPoint(450, 50));
    pBtnAnalyze->SetSize(MiniSize(66, 23));
    pBtnAnalyze->Release();

}

DNSWnd::~DNSWnd()
{
    m_pWinView->Release();
}

void DNSWnd::OnBtnCloseClick(const UIObject* sender, const Type::MiniPoint& pt, MouseButton button, uint keyState)
{
    ::PostQuitMessage(0);
}

void DNSWnd::OnBtnAnalyzeClick(const UIObject* sender, const Type::MiniPoint& pt, MouseButton button, uint keyState)
{
    WSADATA wsaData;
    WSAStartup(MAKEWORD(2, 2), &wsaData);

    addrinfo* answer;
    addrinfo hint;

    memset(&hint, 0, sizeof(addrinfo));
    
    hint.ai_family = AF_INET;
    hint.ai_socktype = SOCK_STREAM;
    hint.ai_protocol = IPPROTO_TCP;

    int ret = getaddrinfo("baidu.com", NULL, &hint, &answer);
    if (ret != 0)
    {
        MessageBox(NULL, L"getaddrinfo failed!", L"DNSDemo", MB_OK);
        return;
    }

    for (addrinfo* cur = answer; cur != NULL; cur = cur->ai_next)
    {
        char ipstr[16];
        inet_ntop(AF_INET, &(((sockaddr_in*)(cur->ai_addr))->sin_addr), ipstr, 16);
        MessageBoxA(NULL, ipstr, "DNSDemo", MB_OK);
    }

    freeaddrinfo(answer);
}